// <editor-fold defaultstate="collapsed" desc="GNU GPLv3 Header">
/*
 * File:   Main.java
 *
 * Copyright (C) 2013 Robert Antoni Buj Gelonch <rbuj@uoc.edu>
 * Copyright (C) 2013 David Megias Jimenez <dmegias@uoc.edu>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
// </editor-fold>
package pcms16leoriolpareraextracteralaw;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import uoc.libcompression.G711.AlawDecoder;
import uoc.libcompression.G711.AlawEncoder;
import uoc.libwatermarking.sync.FrameOriented.SintSext;
import uoc.libwave.WaveFormatNonPCMByteAlaw;
import uoc.libwave.WaveFormatPCMShort;

/**
 *
 * @author Robert Antoni Buj Gelonch <rbuj@uoc.edu>
 * @version 1.0
 * @since 2013-09-09
 */
public class Main {

    private static short FRAME_SIZE = 256;
    /* Syn params*/
    private static int SYN_MESSAGE = 0x4b871e2d;
    private static int SYN_NBITS = 32;
    private static int SYN_SAMPLES_PER_BIT = 4;
    /* Mark params*/
    private static int MARK_BITS_TO_CODE = 8;
    private static int MARK_SPEC_SAMPLES_PER_BIT = 32;
    private static byte MARK_KEY = 7;

    /**
     *
     * @param lframe
     * @return
     */
    private static byte extractMethod(List<Short> lframe) {
        short extractedByte = 0;
        short temp;
        int nextBlock = 0;
        for (int i = 0; i < MARK_BITS_TO_CODE; i++) {
            extractedByte >>>= 1;
            temp = (short) ((getHidenBit(nextBlock, lframe) == 0x01) ? 0x80 : 0x00);
            extractedByte = (short) (extractedByte | temp);
            nextBlock += MARK_SPEC_SAMPLES_PER_BIT;
        }
        return (byte) extractedByte;
    }

    /**
     *
     * @param nextBlock
     * @param lframe
     * @return
     */
    private static byte getHidenBit(int start, List<Short> lframe) {
        AlawEncoder alawEncoder = new AlawEncoder();
        // from 16 bits-signed to 13 bits-signed
        short sample = (short) (lframe.get(start) >> 3);
        // get the compressed value
        byte compressed = alawEncoder.compress(sample);
        // get LSB
        return (byte) (compressed & 0x01);
    }

    /**
     * @param args the command line arguments
     * @since 2013-08-20
     */
    public static void main(String[] args) throws IOException {
        if (args.length < 2) {
            System.err.println("Must supply filenames:");
            System.err.println("java -jar PCM-S16-LE-OriolParera-extracter.jar"
                    + " input.wav output.wav");
            System.exit(1);
        }
        String strSrcFilePath = args[0];
        String strDstFilePath = args[1];
        try {

            // Load Alaw wave file
            WaveFormatNonPCMByteAlaw AlawWaveData =
                    new WaveFormatNonPCMByteAlaw(strSrcFilePath);

            // Convert Alaw wave data to PCM S16 LE wave data
            AlawDecoder alawDecoder = new AlawDecoder();
            byte alawSample;
            short wChannels = AlawWaveData.getWChannel();
            int lenght = AlawWaveData.getNumSamples();
            int dwSamplesPerSec = AlawWaveData.getDwSamplesPerSec();
            short[][] expanded = new short[wChannels][lenght];
            short res;
            for (short i = 0; i < wChannels; i++) {
                for (int j = 0; j < lenght; j++) {
                    alawSample = AlawWaveData.getSample((short) (i + 1), j);
                    // get the compressed value
                    res = alawDecoder.expandTransmission(alawSample);
                    expanded[i][j] = (short) (res * 8);
                }
            }
            WaveFormatPCMShort waveData  = new WaveFormatPCMShort(expanded,
                    lenght, wChannels, dwSamplesPerSec);

            // Extract sync and watermark
            short wChannel = (short) 1;
            List<Short> lframe = new ArrayList<Short>();
            SintSext watermark_sync = new SintSext(SYN_MESSAGE, SYN_NBITS, SYN_SAMPLES_PER_BIT);
            byte extracted;
            // Search the sync mark
            for (int i = 0; i < waveData.getNumSamples() - watermark_sync.size(); i++) {
                waveData.getFrame(i, watermark_sync.size(), wChannel, lframe);
                if (lframe.size() == watermark_sync.size()) {
                    if (watermark_sync.testSynMark(lframe)) {
                        // the search has been successful
                        System.out.println("Sync mark found at pos : " + i);
                        i += watermark_sync.size();
                        lframe.clear();
                        waveData.getFrame(i, FRAME_SIZE, wChannel, lframe);
                        if (lframe.size() == FRAME_SIZE) {
                            // get the watermarking message
                            extracted = extractMethod(lframe);
                            System.out.println("Secret : " + extracted);
                        }
                        i += lframe.size();
                    }
                }
                lframe.clear();
            }
            // save the wave file
            waveData.saveToFile(strDstFilePath);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
